﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Antu.WebControls;
using Antu.Core.Components;
using Antu.Core.Services;
using System.Web.UI.WebControls;
using EluZSProvider;
using System.Web;
using System.Data;

namespace WebSys.UI.Control.ZhengShou
{
    public class ZS_BCJDLRAddControl : MPBasicTemplate
    {
        EluZSDataProvider _EluZSDataProvider = (EluZSDataProvider)ProviderService.ProviderServiceMange.GetProvider("EluZSProvider");
        public string userid = string.Empty;
        DropDownList ddlSZQ, ddlJAQK, ddlFYSLJG, ddlXYFYSLJG, ddlFYZXQK, ddlXYFYZXQK;
        MPCalendar txtSLSJ;
        TextBox txtSQR;//征收人
        TextBox txtBSQR;//被征收人
        TextBox 征片, 征年, 征号, txtIID;
        TextBox txtCASEID;
        MPCalendar txtCUIGAOFACHUDATE,txtCUIGAOSONGDADATE,txtQIANGZHIDATE,txtTINGZHENGDATE,txtXYQIANGZHIDATE,txtXYTINGZHENGDATE;        

        protected override void OnLoad(EventArgs e)
        {
            if (HttpContext.Current.Session["UserID"] == null)
            {
               // Antu.Utilities.UtilitiesPage.AlertDialogClear("登录超时，请重新登录！", "window.parent.location.href('../login.aspx');");
            }
            else
            {
                userid = HttpContext.Current.Session["UserID"].ToString();
            }
            CainBo.Master.Header.RegistAjaxScripts(typeof(ZS_BCJDLRAddControl));
            //MPHeader.RegistAjaxScripts(typeof(ZS_BCJDLRAddControl));
            base.OnLoad(e);
            BindData();
            ddlJAQK.SelectedIndexChanged += new EventHandler(ddlJAQK_SelectedIndexChanged);
           // ddlSZQ.SelectedIndexChanged += new EventHandler(ddlSZQ_SelectedIndexChanged);
            MPPersistence Persistence1 = (MPPersistence)FindControl("Persistence1");
            Panel panel1 = (Panel)FindControl("panel1");
            if (!base.Page.IsPostBack)
            {
                BindDLL();
                Persistence1.Table = "ZS_CASE_REGISTER";
                Persistence1.Key = "ID";
                Persistence1.KeyValue = HttpContext.Current.Request["ID"];
                Persistence1.ConnStr = _EluZSDataProvider.GetConnectionString();

               
                #region 如果IID存在，加载原有内容
                string strIId = base.Page.Request["IID"];
                if (!string.IsNullOrEmpty(strIId))
                {
                    string sql = "select id from zs_case_register where iid='" + strIId + "'";
                    string strId = _EluZSDataProvider.GetSomeWhere("(" + sql + ")", "*", " 1=1 ");
                    if (!string.IsNullOrEmpty(strId))
                    {
                        Persistence1.KeyValue = strId;
                    }
                    //TextBox txtCASEID = (TextBox)panel1.FindControl("txtCASEID");
                    txtIID = (TextBox)panel1.FindControl("txtIID");
                    TextBox txtQWSX = (TextBox)panel1.FindControl("txtQWSX");
                    //txtCASEID.Text = strIId;
                    txtIID.Text = strIId;
                   // txtQWSX.Visible = false;
                    txtQWSX.Attributes.Add("style", "display:none");
                    base.Page.ClientScript.RegisterStartupScript(this.GetType(), "disttable", "<script>disttable();</script>");
                    string sql1 = "select 关联ID from xt_instance_ext where iid='" + strIId + "'";
                    string strPJID = _EluZSDataProvider.GetSomeStr("(" + sql1 + ")", "*", "");
                    BindZSRandBZSR(strIId);//代入征收人和被征收人
                    if (!string.IsNullOrEmpty(strPJID))
                    {
                        string psql = @"select  (select keyvalue from zs_params where name='区属' and keyname =
(select 区属 from zs_project where id in (select pid from zs_prono where id=t.pid))) 区属,
(select 征收许可证号 from zs_prono where id=t.pid) 征收决定号
 from zs_zzbcjfenhu t where id='" + strPJID + "'";
                        DataTable dt = _EluZSDataProvider.GetOneDs("(" + psql + ")", "*", "").Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            TextBox txtXKZH = (TextBox)FindControl("txtXKZH");
                            txtXKZH.Text = dt.Rows[0]["征收决定号"].ToString();
                            ddlSZQ.SelectedValue = dt.Rows[0]["区属"].ToString();
                        }


                        string sql2 = @"select * from zs_zsperson where id = 
( select ZSPID from zs_zzbcjfenhu where id='" + strPJID + "')";
                        DataTable dt2 = _EluZSDataProvider.GetOneDs("(" + sql2 + ")", "*", "").Tables[0];
                        if (dt2.Rows.Count > 0)
                        {
                            TextBox txtFWDZ = (TextBox)FindControl("txtFWDZ");
                            TextBox txtJZMJ = (TextBox)FindControl("txtJZMJ");
                            txtFWDZ.Text = dt2.Rows[0]["房屋坐落"].ToString();
                            txtJZMJ.Text = dt2.Rows[0]["房屋建筑面积"].ToString();
                        }
                        string sql3 = @"select * from zs_zzbcjfenhu where id='" + strPJID + "'";
                        DataTable dt3 = _EluZSDataProvider.GetOneDs("(" + sql3 + ")", "*", "").Tables[0];
                        if (dt3.Rows.Count > 0)
                        {
                            double temp1 = 0, temp2 = 0, temp3 = 0, temp4 = 0;

                            if (!string.IsNullOrEmpty(dt3.Rows[0]["ZZ评估总价"].ToString()))
                            {
                                temp1 = Convert.ToDouble(dt3.Rows[0]["ZZ评估总价"].ToString().Trim());
                            }
                            if (!string.IsNullOrEmpty(dt3.Rows[0]["YY评估总价"].ToString()))
                            {
                                temp2 = Convert.ToDouble(dt3.Rows[0]["YY评估总价"].ToString().Trim());
                            }
                            if (!string.IsNullOrEmpty(dt3.Rows[0]["FYY评估总价"].ToString()))
                            {
                                temp3 = Convert.ToDouble(dt3.Rows[0]["FYY评估总价"].ToString().Trim());
                            }
                            if (!string.IsNullOrEmpty(dt3.Rows[0]["ZS室内装饰装修评估补偿金额合计"].ToString()))
                            {
                                temp4 = Convert.ToDouble(dt3.Rows[0]["ZS室内装饰装修评估补偿金额合计"].ToString().Trim());
                            }

                            TextBox txtPGJE = (TextBox)FindControl("txtPGJE");
                            txtPGJE.Text = (temp1 + temp2 + temp3 + temp4).ToString();
                        }

                    }
                }
                #endregion
               
            }
            Persistence1.BindControl = panel1;
#region 复制
            string action = base.Page.Request["action"];
            string strID = base.Page.Request["ID"];
            if (action == "copy")
            {
                EluZSProvider.CASE_REGISTER caseregister = _EluZSDataProvider.GetCASE_REGISTER(strID);
                caseregister.ID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                string caseid = caseregister.CASEID;
                bool copy = _EluZSDataProvider.SaveCaseRegister("", caseregister);
                if (copy) { Antu.Utilities.UtilitiesPage.AlertDialog("复制成功！", "window.location.href('ZS_BCJDLR.aspx');"); }
            }
#endregion
            if (!string.IsNullOrEmpty(base.Page.Request["IID"]))
            {
                base.Page.ClientScript.RegisterStartupScript(this.GetType(), "disttable", "<script>disttable();</script>");
            }
            //txtSLSJ.Text = DateTime.Now.ToShortDateString();//将受理时间变成当前时间       

        }

        #region 得到征收人和被征收人
        /// <summary>
        /// 得到征收人和被征收人,并给征收人和被征收人文本框赋值
        /// </summary>
        /// <param name="_id"></param>
        void BindZSRandBZSR(string _id)
        {
            string sql = @"select * from zs_project where id=(
select pid from zs_prono where id =(select PID from zs_zzbcjfenhu where id= 
 (select 关联ID from xt_instance_ext  where iid='" + _id + "')))";//得到征收人
            DataTable dt = _EluZSDataProvider.GetOneDs("(" + sql + ")", "*", "").Tables[0];
            if (dt.Rows.Count > 0)
            {
                txtSQR.Text = dt.Rows[0]["征收实施单位"].ToString();
            }
            string sql2 = @"select * from zs_zsperson where id = 
( select ZSPID from zs_zzbcjfenhu where id= 
(select 关联ID from xt_instance_ext where iid='" + _id + "'))";
            DataTable dt2 = _EluZSDataProvider.GetOneDs("(" + sql2 + ")", "*", "").Tables[0];
            if (dt2.Rows.Count > 0)
            {
                txtBSQR.Text = dt2.Rows[0]["产权人"].ToString();
            }
        }
#endregion

        #region 查找页面控件
        protected void BindData()
        {
            Button btn_Insert = (Button)FindControl("btn_Insert");
            btn_Insert.Click += new EventHandler(btn_Insert_Click);
            ddlSZQ = (DropDownList)FindControl("ddlSZQ");
            ddlJAQK = (DropDownList)FindControl("ddlJAQK");
            ddlFYSLJG = (DropDownList)FindControl("ddlFYSLJG");
            ddlXYFYSLJG = (DropDownList)FindControl("ddlXYFYSLJG");
            ddlFYZXQK = (DropDownList)FindControl("ddlFYZXQK");
            ddlXYFYZXQK = (DropDownList)FindControl("ddlXYFYZXQK");
            txtSLSJ = (MPCalendar)FindControl("txtSLSJ");

            txtSQR = (TextBox)FindControl("txtSQR");
            txtBSQR = (TextBox)FindControl("txtBSQR");
            征片 = (TextBox)FindControl("征片");
            征年 = (TextBox)FindControl("征年");
            征号 = (TextBox)FindControl("征号");
            txtCASEID = (TextBox)FindControl("txtCASEID");
            // MPCalendar txtCUIGAOFACHUDATE,txtCUIGAOSONGDADATE,txtQIANGZHIDATE,txtTINGZHENGDATE,txtXYQIANGZHIDATE,txtXYTINGZHENGDATE;
            txtCUIGAOFACHUDATE = (MPCalendar)FindControl("txtCUIGAOFACHUDATE");
            txtCUIGAOSONGDADATE = (MPCalendar)FindControl("txtCUIGAOSONGDADATE");
            txtQIANGZHIDATE = (MPCalendar)FindControl("txtQIANGZHIDATE");
            txtTINGZHENGDATE = (MPCalendar)FindControl("txtTINGZHENGDATE");
            txtXYQIANGZHIDATE = (MPCalendar)FindControl("txtXYQIANGZHIDATE");
            txtXYTINGZHENGDATE = (MPCalendar)FindControl("txtXYTINGZHENGDATE");
            //征片.TextChanged += new EventHandler(征片_TextChanged);
            //征年.TextChanged += new EventHandler(征年_TextChanged);
            //征片.AutoPostBack = true;
            //征年.AutoPostBack = true;
        }

        void 征年_TextChanged(object sender, EventArgs e)
        {
            GetHao(征片.Text.Trim(),征年.Text.Trim());
        }

        void 征片_TextChanged(object sender, EventArgs e)
        {
            GetHao(征片.Text.Trim(), 征年.Text.Trim());
        }
        #endregion

        #region 保存
        protected void btn_Insert_Click(object sender, EventArgs e)
        {           
            txtCASEID.Text = 征片.Text.Trim() + "征补字（" + 征年.Text.Trim() + "）第" +
                征号.Text.Trim() + "号";

            string c = _EluZSDataProvider.GetOneStr("ZS_CASE_REGISTER", "CASEID", "IID", base.Page.Request["IID"]);
            if (txtCASEID.Text.Trim()!=c)
            {
                string txt = _EluZSDataProvider.GetOneStr("ZS_CASE_REGISTER", "count(*)", "CASEID", txtCASEID.Text.Trim());
                if (txt == "0")
                {
                    MPPersistence Persistence1 = (MPPersistence)FindControl("Persistence1");
                    Persistence1.Update();
                    string url = "ZS_BCJDLRAdd.aspx?ID=" + Persistence1.KeyValue + "&action=edit&flag=back&IID=" + HttpContext.Current.Request["IID"];
                    Antu.Utilities.UtilitiesPage.AlertDialog("保存成功！", "window.parent.CloseTab();");
                }
                else
                {
                    base.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('案件编号已存在')</script>");
                }
            }
            else
            {
                MPPersistence Persistence1 = (MPPersistence)FindControl("Persistence1");
                Persistence1.Update();
                Antu.Utilities.UtilitiesPage.AlertDialog("保存成功！", "window.parent.CloseTab();");
            }
                       
        }
#endregion

        #region 绑定DDL
        protected void BindDLL()
        {
            List<EluZSProvider.Params> _params = _EluZSDataProvider.GetParams("区属");
            ddlSZQ.DataSource = _params;
            ddlSZQ.DataValueField = "keyvalue";
            ddlSZQ.DataTextField = "keyname";
            ddlSZQ.DataBind();
            List<EluZSProvider.Params> _params1 = _EluZSDataProvider.GetParams("结案情况");
            EluZSProvider.Params item1 = new Params();
            _params1.Insert(0, item1);
            ddlJAQK.DataSource = _params1;
            ddlJAQK.DataValueField = "keyvalue";
            ddlJAQK.DataTextField = "keyname";
            ddlJAQK.DataBind();
            //默认绑定是正在审理
            string sql = "Select keyvalue From zs_params Where Name ='结案情况' And keyname='正在审理'";
            ddlJAQK.SelectedValue = _EluZSDataProvider.GetSomeStr("(" + sql + ")", "*", "");
            List<EluZSProvider.Params> _params2 = _EluZSDataProvider.GetParams("裁定结果");
            EluZSProvider.Params item2 = new Params();
            _params2.Insert(0, item2);
            ddlFYSLJG.DataSource = _params2;
            ddlFYSLJG.DataValueField = "keyvalue";
            ddlFYSLJG.DataTextField = "keyname";
            ddlFYSLJG.DataBind();
            ddlXYFYSLJG.DataSource = _params2;
            ddlXYFYSLJG.DataValueField = "keyvalue";
            ddlXYFYSLJG.DataTextField = "keyname";
            ddlXYFYSLJG.DataBind();
            List<EluZSProvider.Params> _params3 = _EluZSDataProvider.GetParams("执行情况");
            EluZSProvider.Params item3 = new Params();
            _params3.Insert(0, item3);
            ddlFYZXQK.DataSource = _params3;
            ddlFYZXQK.DataValueField = "keyvalue";
            ddlFYZXQK.DataTextField = "keyname";
            ddlFYZXQK.DataBind();
            ddlXYFYZXQK.DataSource = _params3;
            ddlXYFYZXQK.DataValueField = "keyvalue";
            ddlXYFYZXQK.DataTextField = "keyname";
            ddlXYFYZXQK.DataBind();
        }
#endregion

        #region OnPreRender
        protected override void OnPreRender(EventArgs e)
        {
            if (!base.Page.IsPostBack)
            {
                if (string.IsNullOrEmpty(txtSLSJ.Text.Trim()))
                {
                    txtSLSJ.Text = DateTime.Now.ToShortDateString();
                }                
                if (txtCASEID.Text.Trim().Length > 13)
                {
                    string caseid=txtCASEID.Text.Trim();
                    征片.Text = txtCASEID.Text.Trim().Substring(0, caseid.IndexOf('征'));//取得第一个字
                    征年.Text = txtCASEID.Text.Trim().Substring(caseid.IndexOf('（')+1, caseid.IndexOf('）')-caseid.IndexOf('（')-1);//取得第二个进行显示
                    征号.Text = txtCASEID.Text.Trim().Substring(caseid.IndexOf('第')+1, caseid.IndexOf('号') - caseid.IndexOf('第')-1);//取得第三个数字
                }
                else
                {
                    征片.Text = ddlSZQ.SelectedItem.Text.ToString().Substring(0, 1);
                }
                
            }
            
        }
#endregion

        #region  当结案情况选择为 “已经裁决” 时，催告栏目、提交法院、先于提交法院栏目才可以编辑，其他情况不可以编辑
        public void ddlJAQK_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

       #endregion

        #region 案件号的第一个字单独提取到输入框前，可以根据所在区变化而变化，为所在区的名称第一个字
        public void ddlSZQ_SelectedIndexChanged(object sender, EventArgs e)
        {
           
           // HttpContext.Current.Response.Write(ddlSZQ.SelectedValue);

            //获得所在区的第一个字
            string qs = ddlSZQ.SelectedItem.Text.ToString();
            string t = qs.Substring(0, 1);
            //改变txtCASEID的第一个字，即：改变征片.text
            征片.Text = t;
            GetHao(征片.Text.Trim(), 征年.Text.Trim());
        }
        #endregion 

        #region         
        public void GetHao(string szq,string nian)
        {
            try
            {
                if (!string.IsNullOrEmpty(szq)&&!string.IsNullOrEmpty(nian))
                {
                    string sql =string.Format(@"select max(case
         when length(caseid)>13 then replace(substr(caseid,12,length(caseid)),'号','') 
         else ''
       end
)
from ZS_CASE_REGISTER where szq=(select keyvalue from zs_params where keyname like '{0}%' and name='区属')
and (case 
        when length(caseid)>13 then substr(caseid,instr(caseid,'（')+1,(instr(caseid,'）')-instr(caseid,'（')-1))
        else ''
    end
)='{1}'",szq,nian);
                    string h = _EluZSDataProvider.GetString(sql);
                    if (string.IsNullOrEmpty(h))
                    {
                        征号.Text = "0001";
                    }
                    else
                    {
                        int zh = Convert.ToInt32(h);
                        if (zh<9)
                        {
                            征号.Text ="000"+ (Convert.ToInt32(h) + 1).ToString();
                        }
                        else if (zh<99)
                        {
                            征号.Text ="00"+(Convert.ToInt32(h)+1).ToString();
                        }
                        else if (zh<999)
                        {
                            征号.Text ="0"+(Convert.ToInt32(h)+1).ToString();
                        }
                        else
                        {
                            征号.Text = (Convert.ToInt32(h) + 1).ToString();
                        }
                        
                    }
                   
                }
               
            }
            catch (Exception)
            {
                
                throw;
            }
            
        }
        #endregion 


        [Antu.Core.Ajax.AjaxMethod()]
        public static string GetStrHao(string szq, string nian)
        {
            EluZSDataProvider _EluZSDataProvider = (EluZSDataProvider)ProviderService.ProviderServiceMange.GetProvider("EluZSProvider");
            string sh ="";
            try
            {
                if (!string.IsNullOrEmpty(szq) && !string.IsNullOrEmpty(nian))
                {
                    string sql = string.Format(@"select max(case
         when length(caseid)>13 then replace(substr(caseid,12,length(caseid)),'号','') 
         else ''
       end
)
from ZS_CASE_REGISTER where szq=(select keyvalue from zs_params where keyname like '{0}%' and name='区属')
and (case 
        when length(caseid)>13 then substr(caseid,instr(caseid,'（')+1,(instr(caseid,'）')-instr(caseid,'（')-1))
        else ''
    end
)='{1}'", szq, nian);
                    string h = _EluZSDataProvider.GetString(sql);
                    if (string.IsNullOrEmpty(h))
                    {
                        sh = "0001";
                    }
                    else
                    {
                        int zh = Convert.ToInt32(h);
                        if (zh < 9)
                        {
                            sh = "000" + (Convert.ToInt32(h) + 1).ToString();
                        }
                        else if (zh < 99)
                        {
                            sh = "00" + (Convert.ToInt32(h) + 1).ToString();
                        }
                        else if (zh < 999)
                        {
                            sh = "0" + (Convert.ToInt32(h) + 1).ToString();
                        }
                        else
                        {
                            sh = (Convert.ToInt32(h) + 1).ToString();
                        }

                    }

                }

            }
            catch (Exception)
            {

                throw;
            }
            return sh;
        }

    }
}


